package my.jwds.p405;

public class ToHex {
    public static void main(String[] args) {
        ToHex obj = new ToHex();
        System.out.println(obj.toHex(-2));
    }
    char[] hexChar = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
    public String toHex(int num) {
        if (num == 0)return "0";
        int [] charIndex = {0,0,0,0,0,0,0,0};
        int index = 7;
        if (num < 0){
            num = Integer.MAX_VALUE - (num * -1) +1;
            charIndex[0] = 8;
        }
        while(num != 0){
            charIndex[index--] += num%16;
            num/=16;
        }
        StringBuilder sb = new StringBuilder();
        boolean zeroShow = false;
        for (int i = 0; i < charIndex.length; i++) {
            if (charIndex[i] != 0 || zeroShow){
                zeroShow = true;
                sb.append(hexChar[charIndex[i]]);
            }
        }
        return sb.toString();
    }
}
